<?php
namespace app\store\model;
use app\common\model\LiveRoom as LiveRoomModel;

/**
 * 小程序直播间模型
 */
class LiveRoom extends LiveRoomModel
{
    /**
     * 添加
     */
    public function add($data)
    {
        if (!isset($data['share_name']) || empty($data['share_name'])) {
            $this->error = '请上传分享卡片封面图片';
            return false;
        }
		if (!isset($data['cover_name']) || empty($data['cover_name'])) {
            $this->error = '请上传直播间背景墙图片';
            return false;
        }
		$data['start_time'] = strtotime($data['start_time']);
		$data['end_time'] = strtotime($data['end_time']);
		//直播时间验证
		if($data['start_time']<(time()+600)){
			$this->error = '开播时间最早是十分钟后';
            return false;
		}
		if($data['start_time'] > $data['end_time']){
			$this->error = '结束时间要大于开始时间，最大不超过12个小时';
            return false;
		}
		if(($data['start_time']+3600*12)<=$data['end_time']){
			$this->error = '开始和结束时间要在12个小时范围内';
            return false;
		}
		$data['cover_media'] = up_temp_material($data['cover_name']);
		$data['share_media'] = up_temp_material($data['share_name']);
        $data['wxapp_id'] = self::$wxapp_id;
		//在微信端创建直播间
		$result = $this->addRoom($data);
		if($result['errcode']!= 0){
			$this->error = wx_err_msg($result['errcode']);
			return false;
		}
		$data['roomid'] = $result['roomId'];
        return $this->allowField(true)->save($data);		
    }

    /**
     * 编辑
     */
    public function edit($data)
    {
        return $this->allowField(true)->save($data) !== false;
    }

    /**
     * 删除
     */
    public function remove()
    {
        return $this->delete();  
    }
	
	/**
     * 同步微信端
     */
    public function refresh()
    {
		
		//获取云端记录
        $access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/wxa/business/getliveinfo?access_token='.$access_token;
		$data =['start' => 0,'limit' => 99];
		$result = json_decode(http_post($url,$data),true);
		if($result['errcode']!=0){
			$this->error = wx_err_msg($result['errcode']);
			return false;
		}elseif($result['errcode']==1){
			$this->delete();//删除本地直播间
			$this->error = '微信端未创建直播房间';
			return false;
		}
		//过滤新增数据
		//直播间状态。101：直播中，102：未开始，103已结束，104禁播，105：暂停，106：异常，107：已过期
		for($n=0;$n<sizeof($result['room_info']);$n++){
			if($result['room_info'][$n]['live_status']!=107){
				$model = new LiveRoomModel;
				if($room = LiveRoom::getRoom($result['room_info'][$n]['roomid'])){
					$room->save([
					'name' => $result['room_info'][$n]['name'],
					'roomid' => $result['room_info'][$n]['roomid'],
					'cover_img' => $result['room_info'][$n]['cover_img'],
					'share_img' => $result['room_info'][$n]['share_img'],
					'start_time' => $result['room_info'][$n]['start_time'],
					'end_time' => $result['room_info'][$n]['end_time'],
					'anchor_name' => $result['room_info'][$n]['anchor_name'],
					'goods' => $result['room_info'][$n]['goods'],
					'live_status' => $result['room_info'][$n]['live_status'],
					]);
				}else{
					$result['room_info'][$n]['wxapp_id'] = self::$wxapp_id;
					$model->allowField(true)->save($result['room_info'][$n]);
				}
			}
		}
		return true;
    }
	
	/**
     * 添加直播间
     */
    private function addRoom($data)
    {
		$headers = array(
            'Content-Type: application/json',
        );
        $access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/wxaapi/broadcast/room/create?access_token='.$access_token;
		$room =[
			'name' => $data['name'],
			'coverImg' => $data['cover_media'],
			'shareImg' => $data['share_media'],
			'startTime' => $data['start_time'],
			'endTime' => $data['end_time'],
			'anchorName' => $data['anchor_name'],
			'anchorWechat' => $data['anchor_wechat'],
			'type' => $data['type'],
			'screenType' => $data['screen_type'],
			'closeLike' => $data['close_like'],
			'closeGoods' => $data['close_goods'],
			'closeComment' => $data['close_comment']
		];
		return json_decode(http_post($url,$room,$headers),true);
    }
}
